/**
 * 
 */
package xiaojian.toolkit.transport.codec;

import java.io.UnsupportedEncodingException;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author isdom
 *
 */
public class MinaConstantTextDecoder extends CumulativeProtocolDecoder {

    @SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(MinaConstantTextDecoder.class);

    private	static final String	ENCODING = "UTF-8";
    
    private	byte[]	text;
    private int dumpBytes = 256;
    private	boolean	isDebugEnabled;
    
	/* (non-Javadoc)
     * @see org.apache.mina.filter.codec.CumulativeProtocolDecoder#doDecode(org.apache.mina.core.session.IoSession, org.apache.mina.core.buffer.IoBuffer, org.apache.mina.filter.codec.ProtocolDecoderOutput)
     */
    @Override
    protected boolean doDecode(IoSession session, IoBuffer in,
            ProtocolDecoderOutput out) throws Exception {
        
        if ( in.remaining() < text.length ) {
            return false;
        }
        byte[] recvd = new byte[text.length];
        in.get(recvd);
        out.write( new String(recvd, ENCODING) );
        
        return true;
    }

   
    /**
     * @param dumpBytes the dumpBytes to set
     */
    public void setDumpBytes(int dumpBytes) {
        this.dumpBytes = dumpBytes;
    }
    
	public int getDumpBytes() {
		return dumpBytes;
	}

	public boolean isDebugEnabled() {
		return isDebugEnabled;
	}

	public void setDebugEnabled(boolean isDebugEnabled) {
		this.isDebugEnabled = isDebugEnabled;
	}

	/**
	 * @return the text
	 * @throws UnsupportedEncodingException 
	 */
	public String getText() throws UnsupportedEncodingException {
		return new String(text, ENCODING);
	}

	/**
	 * @param text the text to set
	 * @throws UnsupportedEncodingException 
	 */
	public void setText(String text) throws UnsupportedEncodingException {
		this.text = text.getBytes(ENCODING);
	}

}
